<?php
class Sign {


    /**
     * 格式化参数格式化成url参数
     */
    private static function toUrlParams($data)
    {
        $buff = "";
        foreach ($data as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 生成签名
     * @param $params 数据数组
     * @param $key key值
     * @return string 返回签名
     */
    public static function makeSign($params,$key) {
        //按字典序排序
        ksort($params);

        //生成加密字符串
        $string = self::toUrlParams($params);
        //追加key值在末尾
        $string = $string . "&key=".$key;

        //生成签名
        $string = hash_hmac("sha256",$string ,$key);

        //转换大写
        return strtoupper($string);
    }

    /**
     * 验证签名,直接调用makePublicKey生成key
     */
    public static function verifySign($params,$appId,$appKey) {

        if(!isset($params['sign'])) {
            return FALSE;
        }
        $key = self::makePublicKey($appId,$appKey);
        $sign = self::makeSign($params,$key);

        if($params['sign'] == $sign)
            return TRUE;

        return FALSE;
    }

    /**
     * 生成key
     */
    public static function makePublicKey($appId,$appKey) {
        return md5($appId.'GAME_MAKERS'.$appKey);
    }
}